<?php

    require 'functions.php';

    if (!is_numeric($_POST['friend_id']))
    {
        die(json_encode(array('error' => 'no friend id')));
//        $friend_id = '1591352763';  //szczepan
//        $friend_id = '502586235';   //ragni
    }
    else
    {
        $friend_id = $_POST['friend_id'];
    }
    
    if (DEBUG==true)
    {
        $output['post'] = json_encode($_POST);
    }
    
    $db = DBControl::getInstance();

    $facebook = new Facebook(array(
      'appId'  => '375403899218810',
      'secret' => 'f9f39624aa0bc78b05a15dcfbfb69abb'
     ));
    
    //facebook likes handling
    $user = $facebook->getUser();
    if ($user) 
    {
        try 
        {
            // Proceed knowing you have a logged in user who's authenticated.
            $fbresult = $facebook->api('/me?fields=friends.uid('.$friend_id.').fields(birthday,gender,likes,name),likes,gender,birthday');
        } 
        catch (FacebookApiException $e)
        {
            $params = array(
                'redirect_uri' => 'http://apps.facebook.com/findgiftsforfriends/'
            );
            die(json_encode(array('error' => 'oauth_exception','redirect_url' => $facebook->getLoginUrl($params))));
            $user = null;
        }
    }
    //save fb_user_id
//    $_SESSION['fb_user_id'] = $fbresult['id'];
    
    //handle likes
    if (!empty($fbresult['friends']['data'][0]['likes']['data']))
    {
        //$mapping from functions.php
        $user_weights = getWeightsVector($fbresult['friends']['data'][0]['likes']['data'], $mapping);
        
        $tmpWeights = $user_weights;
        array_push($tmpWeights, LIKED_PRODUCT_COUNT);

        //$weight_likes_query from functions.php
        $result = $db ->PDOquery($weight_likes_query, $tmpWeights);

        $output['likes'] = $result;
    }
    else 
    {
        $output['likes'] = NULL;
    }

    //gender handling
    if($fbresult['friends']['data'][0]['gender']=='male' || $fbresult['friends']['data'][0]['gender']='female')
    {
        $values = array(
            ($fbresult['friends']['data'][0]['gender']=='male') ? 'M' : 'K',
            LIKED_PRODUCT_COUNT
        );

        $result = $db->PDOquery('SELECT item.id, title, mediumimagelink, amazonurl FROM item JOIN genderrecomendation ON item.id=genderrecomendation.item_id WHERE gender = ? ORDER BY ordernumber LIMIT ?', $values);
        $output['gender'] = $result;
    }
    else
    {
        $output['gender'] = NULL;
    }

    //genderAge handling
    if(($fbresult['friends']['data'][0]['gender']=='male' || $fbresult['friends']['data'][0]['gender']='female') && 
        !empty($fbresult['friends']['data'][0]['birthday']))
    {
        $age = getAge($fbresult['friends']['data'][0]['birthday']);
        $output['additionalInfo']['age'] = $age;
        $values = array(
            ($fbresult['friends']['data'][0]['gender']=='male') ? 'M' : 'K',
            $age,
            LIKED_PRODUCT_COUNT
        );
        $result = $db->PDOquery('SELECT item.id, title, mediumimagelink, amazonurl FROM item JOIN genderagerecomendation ON item.id=genderagerecomendation.item_id WHERE gender = ? AND agegroup_id = (SELECT id FROM agegroup WHERE ? BETWEEN minage AND maxage) ORDER BY ordernumber LIMIT ?', $values);
        $output['genderage'] = $result;
    }
    else
    {
        $output['genderage'] = NULL;
        $output['additionalInfo']['age'] = NULL;
    }

    $output['additionalInfo']['sex'] = ($fbresult['friends']['data'][0]['gender']=='male') ? 'M' : 'K';
    
    //check if user already in db
    $user_info = $db ->PDOquery("SELECT id FROM users WHERE facebook_id = ? LIMIT 1;", array($friend_id));
    if (empty($user_info))
    {
        //add user info
        $insert_data = array(
            (isset($age)) ? $age : null,
            ($fbresult['friends']['data'][0]['gender']=='male') ? 'M' : 'K',
            ($user_weights) ? weightsArrayToString($user_weights) : null,
            $friend_id
        );

        $user_id = $db -> PDOquery('INSERT INTO users (age, gender, weights, facebook_id) VALUES (?,?,?,?) RETURNING id;', $insert_data);
        $user_id = $user_id[0]['id'];
    }
    else
    {
        $user_id = $user_info[0]['id'];
    }
   
    $output['recommendation_id'] = $user_id;
    echo json_encode($output);

?>
